<script setup>
  import { ref } from 'vue'
  import { loginByPasswordApi } from '@/apis/user'
  import { useUserStore } from '@/stores/user'
  defineOptions({
    styleIsolation: 'shared',
  })

  //表单数据
  const formData = ref({
    mobile: '13230000094',
    password: 'abc12345',
  })
  const isAgreement = ref(false)
  //表单校验
  const formRef = ref()
  const formRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请输入手机号' },
        { pattern: '^1[0-9]{10}$', errorMessage: '请输入正确的手机号' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入密码' },
        { pattern: '^[0-9a-zA-Z]{6,16}$', errorMessage: '请输入6-16位密码' },
      ],
    },
  }

  // 提交表单
  const submitForm = async () => {
    try {
      const res = await formRef.value.validate()
      console.log(res)
      if (!isAgreement.value) {
        uni.showToast({
          title: '请先同意用户协议和隐私协议',
          icon: 'none',
        })
        return
      }
      login()
    } catch (error) {
      console.log(error)
    }
  }

  // 登录
  const userStore = useUserStore()
  const login = async () => {
    try {
      const res = await loginByPasswordApi({
        mobile: formData.value.mobile,
        password: formData.value.password,
      })
      userStore.setToken(res.token)
      uni.switchTab({ url: '/pages/index/index' })
      uni.showToast({
        title: '登录成功',
        icon: 'success',
      })
    } catch (error) {
      console.log(error)
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="formRef" :rules="formRules" :model="formData">
    <uni-forms-item name="mobile">
      <uni-easyinput
        v-model="formData.mobile"
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <uni-easyinput
        v-model="formData.password"
        type="password"
        placeholder="请输入密码"
        :input-border="false"
        placeholder-style="color: #C3C3C5"
      />
    </uni-forms-item>
    <view class="agreement">
      <radio :checked="isAgreement" color="#16C2A3" @click="isAgreement = !isAgreement" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>
    <button class="uni-button" @click="submitForm">登 录</button>
    <navigator hover-class="none" class="uni-navigator" url=" "> 忘记密码？ </navigator>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
